<script setup>
import { nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useShowSendEmailDialogStore } from '@/store/showSendEmailDiaolg';
import axios from 'axios'
import { userSendRegisterEmailCheckCodeService } from '@/api/user';
import verify from '@/utils/verify.js' // 导入正则校验工具类
import { getCurrentInstance } from "vue"

// 获取父组件Register传递过来的用户邮箱
let props = defineProps({
  email: {
    type: String,
  },
})

// 获取全局注册的组件
const { proxy } = getCurrentInstance();

// 显示发送邮件框状态
const showSendEmailDiaolgStore = useShowSendEmailDialogStore()

// 关闭发送邮件框方法
const handleSendEmailDialogClose = () => {
  showSendEmailDiaolgStore.setShowSendEmailDialog(false)
}

// 获取图片验证码
const imageCheckCodeUrl = ref()
const getImageCheckCode = () => {
  axios({
    url: '/api/user/user/getRegisterSendEmailImageCheckCode',
    method: 'get',
    responseType: 'blob' //选择接收方式为blob
  }).then((res) => {
    // console.log("res", res)
    imageCheckCodeUrl.value = URL.createObjectURL(res.data)
  }).catch((err) => {
    // console.log("err", err)
  })
}

// 发送邮箱验证码的表单
const formData = ref({
  email: '',
  imageCheckCode: ''
})
const formDataRef = ref()
const rules = {
  email: [
    { required: true, message: "请输入邮箱", trigger: 'blur' },
    { max: 150, message: "邮箱太长", trigger: 'blur' },
    { validator: verify.email, message: "请输入正确的邮箱", trigger: 'blur' }
  ],
  imageCheckCode: [
    { required: true, message: "请输入图形验证码", trigger: 'blur' }
  ],
}

// 发送邮箱验证码
const sendEmailCheckCode = () => {
  formDataRef.value.validate()
    .then(async (res) => {
      console.log("校验通过", res)
      let result = await userSendRegisterEmailCheckCodeService(formData.value)
      // 显示成功
      proxy.Notification.success(result.code === 1 ? '邮箱验证码发送成功' : result.msg)
      // 发送邮件成功后，关闭发送邮件框
      showSendEmailDiaolgStore.setShowSendEmailDialog(false)
    }).catch((err) => {
      console.log("校验没通过，错误原因：", err)
      // 重新获取图片验证码
      getImageCheckCode()
    })
}
// const sendEmailCheckCode = async () => {
//   await formDataRef.value.validate(async (valid) => {
//     if (!valid) {
//       console.log("校验未通过")
//       getImageCheckCode() // 重新获取图片验证码
//       return
//     } else {
//       console.log("校验通过，可以获取邮箱验证码")
//       let res = await userSendRegisterEmailCheckCodeService(formData.value)
//       console.log("邮箱验证码发送结果：", res)
//     }
//   })
// }

onMounted(() => {
  // 获取图片验证码
  getImageCheckCode()
  // 将父组件Register传递过来的用户邮箱赋值给表单
  formData.value.email = props.email
})
</script>

<template>
  <div class="send-email-panel">
    <el-dialog v-model="showSendEmailDiaolgStore.showSendEmailDialog" :close-on-click-modal="false"
      :close-on-press-escape="false" :before-close="handleSendEmailDialogClose" class="send-email-panel">
      <div class="panel-title">发送邮箱验证码</div>
      <div class="panel-form">
        <el-form :model="formData" :rules="rules" ref="formDataRef">
          <!-- 显示一下邮箱 -->
          <el-form-item prop="email">
            <el-input size="large" disabled placeholder="请输入邮箱" v-model="formData.email">
              <template #prefix>
                <span class="iconfont icon-email"></span>
              </template>
            </el-input>
          </el-form-item>
          <!-- 发送邮箱之前的图形验证码 -->
          <el-form-item prop="imageCheckCode" style="width: 100%;">
            <div style="width: 100%;display: flex; justify-content: space-between;">
              <el-input size="large" clearable placeholder="请输入图形验证码" v-model="formData.imageCheckCode">
                <template #prefix>
                  <span class="iconfont icon-check_code"></span>
                </template>
              </el-input>
              <img :src="imageCheckCodeUrl" @click="getSendEmailImageCheckCode"
                style="margin-left: 10px;cursor: pointer;">
            </div>
          </el-form-item>
        </el-form>
      </div>
      <div class="panel-button">
        <button class="send-email-btn" type="button" @click.prevent="sendEmailCheckCode">发送邮箱验证码</button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.send-email-panel {
  width: 500px !important;
}

.send-email-panel .panel-title {
  font-size: 20px;
  padding: 0px 10px 20px;
  color: #252933;
  border-bottom: 1px solid rgba(200, 202, 207, 0.5);
}

.send-email-panel .panel-form {
  padding-top: 10px;
}

.send-email-panel .panel-button .send-email-btn {
  width: 100%;
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
  color: #fff;
  background-color: #67C23A;
  font-size: 16px;
  border: 0px;
}
</style>